<!DOCTYPE html>
<script src="../../resources/js-test.js"></script>
<script src="resources/shared.js"></script>
<script>

description("Confirm that IndexedDB can store an empty File from the Filesystem API");

function prepareDatabase()
{
    db = event.target.result;
    var trans = event.target.transaction;
    evalAndLog("store = db.createObjectStore('storeName')");
    evalAndLog("store.put('value', 'key')");
    trans.onerror = unexpectedErrorCallback;
    trans.onabort = unexpectedAbortCallback;
}

var fileValidation = ".size == 0";
function testEmptyFilesystemFile()
{
    preamble();
    evalAndLog("file = window.emptyFile");
    validateResult("file", fileValidation, cleanupFs);
}

function validateResult(variable, validation, onSuccess)
{
    var keyName = variable + "key";
    debug("");
    debug("validateResult(" + variable + "):");
    shouldBeTrue(variable + validation);
    evalAndLog("transaction = db.transaction('storeName', 'readwrite')");
    evalAndLog("store = transaction.objectStore('storeName')");
    evalAndLog("store.put(" + variable + ", '" + keyName + "')");
    transaction.onerror = unexpectedErrorCallback;
    transaction.onabort = unexpectedAbortCallback;
    var onGetSuccess = function (e) {
      shouldBeTrue("event.target.result" + validation);
      onSuccess();
    }
    transaction.oncomplete = function () {
      doRead(keyName, onGetSuccess);
    }
}

function doRead(keyName, onSuccess)
{
    evalAndLog("transaction = db.transaction('storeName', 'readwrite')");
    evalAndLog("store = transaction.objectStore('storeName')");
    evalAndLog("request = store.get('" + keyName + "')");
    request.onsuccess = onSuccess;
    transaction.onerror = unexpectedErrorCallback;
    transaction.onabort = unexpectedAbortCallback;
}

function fsError(error)
{
    debug("Filesystem error:" + error.name);
    cleanupFs();
}
function fsCreated(fs)
{
    debug("Got FileSystem:" + fs.name);
    window.fileSystem = fs;

    fs.root.getFile("empty.txt", {create: true}, function(entry) {
        entry.file(function(file) {
            window.emptyFile = file;
            indexedDBTest(prepareDatabase, testEmptyFilesystemFile);
        });
    }, fsError);
}

if (window.webkitRequestFileSystem)
    window.webkitRequestFileSystem(TEMPORARY, 100, fsCreated, fsError);
else
    alert("This test requires the FileSystem API");

function cleanupFs()
{
    if (window.fileSystem) {
        var fs = window.fileSystem;
        // cleanupFs shouldn't get called again if an error occurs below.
        window.fileSystem = null;
        fs.root.getFile("empty.txt", {create: false}, function (entry) {
            entry.remove(finishJSTest, fsError);
        }, fsError);
    }
}
</script>
